package org.raymond.iworks.study.mq.rabbitmq.quorum;

import com.rabbitmq.client.*;
import com.rabbitmq.client.impl.DefaultExceptionHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class NormalWorker {
    public static String EXCHANGE_NAME = "ex";
    public static String QUEUE_NAME = "quorum_queue";
    public static String ROUTING_KEY = "rk";
    public static void main(String[] args) throws Exception {
        Connection conn = connection();
        Channel channel = conn.createChannel();

        Map<String, Object> map = new HashMap<>();
        map.put("x-queue-type", "quorum");
        channel.queueDeclare(QUEUE_NAME, true, false, false, map);
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);
        log.info("[*] Waiting for message");

        channel.basicQos(1);

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            log.info(" [x] Normal Received {}:{}", delivery.getEnvelope().getRoutingKey(), message);
            try{
                doWork(message);
            }catch (InterruptedException e){
                log.error("{}: {} will intterrupt.", e.getMessage(), Thread.currentThread().getName());
                Thread.currentThread().interrupt();
            }finally {
                log.info(" [x] Done");
                boolean multiple = false;
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), multiple);
            }
        };

        boolean autoAck = false;
        channel.basicConsume(QUEUE_NAME, autoAck, deliverCallback, consumerTag -> {
            log.info("ConsumerTag-{} cancel", consumerTag);
        });
    }

    private static void doWork(String task) throws InterruptedException {
        if(task.startsWith("interrupted")){
            Thread.currentThread().interrupt();
        }
        for (char ch: task.toCharArray()){
            if(ch=='.') Thread.sleep(10*1000);
        }
    }

    public static Connection connection() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.0.125");
        factory.setPort(5672);
        factory.setUsername("cloud");
        factory.setPassword("cloud123");
        factory.setVirtualHost("/cloud");

        factory.setExceptionHandler(new DefaultExceptionHandler(){
            @Override
            public void handleConsumerException(Channel channel, Throwable exception, Consumer consumer, String consumerTag, String methodName) {
                super.handleConsumerException(channel, exception, consumer, consumerTag, methodName);
                log.info("consumer exception: {}", exception.getMessage());
            }
        });
        return factory.newConnection();
    }
}
